var cf = require("../../../config.js");
var Zan = require('../../../youzan/dist/index');
var util = require("../../../utils/util.js");
var cusmallToken = wx.getStorageSync('cusmallToken');
var baseHandle = require("../../template/baseHandle.js");
var commHandle = require("../../template/commHandle.js");
//获取应用实例
var app = getApp();
Page(Object.assign({}, commHandle, Zan.Toast, baseHandle, {

  /**
   * 页面的初始数据
   */
  data: {
    app: app,
    needUserInfo: true,
    staticResPath: cf.config.staticResPath,
    userImagePath: cf.config.userImagePath,
    extConfig: wx.getExtConfigSync ? wx.getExtConfigSync() : {},
    verType: "coupon", //核销类型
    coupon: {
      title: "",
      money: 100,
      leastCost: 100,
      totalCount: "1",
      getLimitCount: "1",
      timeLimitType: 1,
      effectDay: 1,
      remind: false,
      description: "",
      effectStartTime: "",
      effectEndTime: "",
      discount: "",
      ext1: 1,
      type: 1,
      fromChat: false,
      showFlag: false,
      showActivityTip:false
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var that = this;
    wx.hideShareMenu()
    if ("chatdetail" == options.from) {
      that.setData({
        fromChat: true,
        msgId: options.msgId
      });
    }
    app.getUserInfo(this, options, function(userInfo, res) {
      cusmallToken = wx.getStorageSync('cusmallToken');
      that.setData({
        id: options.id
      });
      var promotionId = options.promotionId;
      if (promotionId) {
        that.getPromotionData(promotionId, function(res) {
          that.setData({
            promotionEid: res.data.model.result.employee.id,
            id: Number(JSON.parse(res.data.model.result.commonPromotion.pageParam).id)
          })
          that.fetchCouponData();
        })
      } else {
        that.fetchCouponData();
      }
      if (options.recordId) {
        that.setData({
          recordId: options.recordId
        });
        that.fetchRecordData();
      }

    });

  },
  //如果是推广活动进入 获取eid
  getPromotionData: function(promotionId, callback) {
    var that = this;
    wx.request({
      url: cf.config.pageDomain + '/applet/mobile/visitcard/commonpromotion/resolve',
      data: {
        cusmallToken: cusmallToken,
        promotionId: promotionId,
        page: 'pages/shopping_mall/coupon/coupon'
      },
      header: {
        'content-type': 'application/json'
      },
      success: function(res) {
        if (0 == res.data.ret) {
          var eId = res.data.model.result.employee.id;
          util.addRelation(eId, cusmallToken, 0);
          that.setData({
            promotionEid: res.data.model.result.employee.id,
            id: Number(JSON.parse(res.data.model.result.commonPromotion.pageParam).id)
          })
          wx.setStorageSync("eId", res.data.model.result.employee.id + "");
          callback && callback(res)
        }else{
          // that.setData({
          //   showActivityTip: true
          // })
          wx.showModal({
            title: '提示',
            content: '您访问的活动不存在',
            showCancel: false,
            success(res) {
              if (res.confirm) {
                console.log('用户点击确定')
              } else if (res.cancel) {
                console.log('用户点击取消')
              }
            }
          })
        }
      }
    })
  },
  handleGetBtnTap: function() {
    var that = this;
    wx.showLoading({
      title: '加载中',
    });
    wx.request({
      url: cf.config.pageDomain + '/applet/mobile/visitcard/coupon/obtainCoupon',
      data: {
        cusmallToken: cusmallToken,
        couponId: that.data.id,
        fromUid: app.globalData.fromuid || "",
        shopUid: app.globalData.shopuid || ""
      },
      header: {
        'content-type': 'application/json'
      },
      success: function(res) {
        if (res.data.ret == 0) {
          that.showZanToast('领取成功，\n赶紧去使用吧');
          wx.hideLoading();
          if (that.data.fromChat) {
            that.chatCouponInvalid();
          } else {

            that.fetchCouponData();
          }
        } else {
          wx.hideLoading();
          that.showZanToast('没领到哦！\n您的单张券已领取达到上限');
          that.fetchCouponData();
        }
      }
    });
  },
  handleUseBtnTap: function() {
    let vm = this;
    if (vm.data.coupon.type != 5 && vm.data.coupon.type != 6 && vm.data.coupon.busiId != "") { //查询商品类型
      if (vm.data.coupon.useLimitType == 1) {
        wx.redirectTo({
          url: '/pages/shopping_mall/detail/detail?id=' + vm.data.coupon.busiId
        });
      } else {
        wx.redirectTo({
          url: '/pages/shopping_mall/channel/channel?id=' + vm.data.coupon.busiId
        });
      }

    } else if (vm.data.coupon.type == 5) {
      wx.showLoading({
        title: '加载中',
      });
      wx.request({
        url: cf.config.pageDomain + '/applet/mobile/visitcard/coupon/useDepositCoupon',
        data: {
          cusmallToken: cusmallToken,
          recordId: vm.data.record.id
        },
        header: {
          'content-type': 'application/json'
        },
        success: function(res) {
          if (res.data.ret == 0) {
            wx.showModal({
              title: '提示',
              showCancel: false,
              content: '已成功存入您的储值余额！',
            })
            vm.fetchRecordData();
            wx.hideLoading();
          } else {
            wx.hideLoading();
            wx.showModal({
              title: '优惠券使用异常',
              showCancel: false,
              content: res.data.msg
            })
          }
        }
      });

    } else if (vm.data.coupon.type == 6) {
      if (vm.data.app.globalData.shopuid) {
        if (!vm.data.appletScene) {
          vm.fetchVerifyQrcodeInfo();
        } else {
          vm.switchPasswordCheck();
        }
      } else {
        vm.toggleQrcodeModal();
      }
    } else {
      wx.redirectTo({
        url: '/pages/shopping_mall/index/index',
      })
    }
  },
  getGoods: function(id, resolve, reject) {
    let that = this;
    cusmallToken = wx.getStorageSync('cusmallToken');
    wx.request({
      url: cf.config.pageDomain + '/applet/mobile/goods/selectGoods',
      data: {
        goodsId: id,
        cusmallToken: cusmallToken
      },
      header: {
        'content-type': 'application/json'
      },
      success: function(res) {
        if (res.data.ret == 0) {

          resolve(res.data)
        } else {
          reject(res.data)
        }
      }
    })
  },
  fetchCouponData: function() {
    var that = this;
    wx.showLoading({
      title: '加载中',
    });
    wx.request({
      url: cf.config.pageDomain + '/applet/mobile/visitcard/coupon/findCouponConfig',
      data: {
        cusmallToken: cusmallToken,
        couponId: that.data.id,
        fromUid: app.globalData.fromuid || "",
        shopUid: app.globalData.shopuid || ""
      },
      header: {
        'content-type': 'application/json'
      },
      success: function(res) {
        if (res.data.ret == 0) {
          var coupon = res.data.model.config;
          if (coupon.effectStartTime) {
            coupon.effectStartTime = util.formatTime(new Date(coupon.effectStartTime));
          }
          if (coupon.effectEndTime) {
            coupon.effectEndTime = util.formatTime(new Date(coupon.effectEndTime));
          }
          if (coupon.extend) {
            coupon.extend = JSON.parse(coupon.extend);
          }
          that.setData({
            coupon: coupon
          });
          that.setData({
            obtainedNum: res.data.model.obtainedNum
          });
          that.setData({
            isExpire: res.data.model.isExpire
          });
          wx.setNavigationBarTitle({
            title: coupon.title
          });
          if (that.data.fromChat && coupon.getLimitCount != -1 && res.data.model.obtainedNum >= coupon.getLimitCount) {
            that.chatCouponInvalid(true);
          }
          that.setData({
            showFlag: true
          })
          wx.hideLoading();
        } else {
          wx.hideLoading();
          wx.showModal({
            title: '获取优惠券信息异常',
            showCancel: false,
            content: res.data.msg
          })
        }
      }
    })

  },

  fetchRecordData: function() {
    var that = this;
    wx.showLoading({
      title: '加载中',
    });
    wx.request({
      url: cf.config.pageDomain + '/applet/mobile/visitcard/coupon/findCouponRecord',
      data: {
        cusmallToken: cusmallToken,
        recordId: that.data.recordId,
        fromUid: app.globalData.fromuid || "",
        shopUid: app.globalData.shopuid || ""
      },
      header: {
        'content-type': 'application/json'
      },
      success: function(res) {
        if (res.data.ret == 0) {
          var record = res.data.model.record;
          if (record.getTime) {
            record.getTime = util.formatTime(new Date(record.getTime));
          }
          that.setData({
            record: record
          });
          var nowTime = new Date();
          if (nowTime >= record.effectStartTime && nowTime <= record.effectEndTime) {
            that.setData({
              canUse: true
            });
          }
          wx.hideLoading();
        } else {
          wx.hideLoading();
          wx.showModal({
            title: '获取优惠券信息异常',
            showCancel: false,
            content: res.data.msg
          })
        }
      }
    })

  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  toggleQrcodeModal: function() {
    var that = this;
    if (that.data.showQrcodePopup) {
      that.setData({
        showQrcodePopup: false
      })
    } else {
      that.setData({
        showQrcodePopup: true
      });
      if (!that.data.appletScene) {
        that.fetchVerifyQrcodeInfo();
      }
    }
  },
  // 获取核销qrcode信息
  fetchVerifyQrcodeInfo: function() {
    var that = this;
    let isSon = that.data.app.globalData.shopuid ? true : false;
    wx.showLoading({
      title: '加载中...',
    })
    wx.request({
      url: cf.config.pageDomain + '/applet/mobile/verifiedclerk/genCouponVerifiedQrCode',
      data: {
        isSon: isSon,
        cusmallToken: cusmallToken,
        page: "pages/verify/coupon_verify",
        recordId: that.data.recordId
      },
      header: {
        'content-type': 'application/json'
      },
      success: function(res) {
        if (res.data.ret == 0) {

          if (that.data.app.globalData.shopuid) { //子店
            that.setData({
              sceneData: JSON.parse(res.data.model.scene)
            });
            that.switchPasswordCheck();
          } else { //主店
            that.setData({
              appletScene: res.data.model.appletScene
            });
            that.setData({
              sceneData: JSON.parse(res.data.model.appletScene.entity || "{}")
            })
          }
        } else {
          wx.hideLoading();
          wx.showModal({
            title: '获取核销qrcode信息异常',
            showCancel: false,
            content: res.data.msg
          })
        }
        wx.hideLoading();
      }
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    var that = this;
    if (that.data.onHide) {
      if (that.data.recordId) {
        that.fetchRecordData();
      }
      that.fetchCouponData();
    }
  },

  gotoIndex: function() {
    wx.navigateTo({
      url: '/pages/shopping_mall/index/index',
    })
  },
  chatCouponInvalid(notReturn) {
    let ctx = this;
    wx.request({
      url: cf.config.pageDomain + '/applet/mobile/visitcard/chatmsg/msgInvalid',
      data: {
        cusmallToken: cusmallToken,
        id: ctx.data.msgId
      },
      header: {
        'content-type': 'application/json'
      },
      success: function(res) {
        if (res.data.ret == 0) {
          if (!notReturn) {
            let pages = getCurrentPages(); //当前页面
            let prevPage = pages[pages.length - 2]; //上一页面

            prevPage.handleRefreshMsg();
            wx.navigateBack({
              delta: 1
            });
          }

        } else {
          wx.showToast({
            title: res.data.msg,
            icon: "none"
          })
        }
        wx.hideLoading();
      }
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {
    this.data.onHide = true;
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角
   */
  onShareAppMessage: function() {
    return {
      title: this.data.coupon.title
    }
  }
}))